<template>
  <div class="customer-service-container">
    <el-card>
      <div slot="header" class="clearfix">
        <span>客服管理</span>
      </div>
      
      <el-tabs v-model="activeTab">
        <el-tab-pane label="会话列表" name="sessions">
          <!-- 搜索工具栏 -->
          <div class="filter-container">
            <el-input
              v-model="listQuery.keyword"
              placeholder="访客名称/最后消息"
              style="width: 200px;"
              class="filter-item"
              clearable
              @keyup.enter.native="handleFilter"
            />
            <el-select
              v-model="listQuery.status"
              placeholder="会话状态"
              clearable
              class="filter-item"
              style="width: 130px"
            >
              <el-option label="进行中" :value="0" />
              <el-option label="已结束" :value="1" />
              <el-option label="已评价" :value="2" />
            </el-select>
            <el-button
              v-waves
              class="filter-item"
              type="primary"
              icon="el-icon-search"
              @click="handleFilter"
            >
              搜索
            </el-button>
          </div>

          <!-- 会话列表表格 -->
          <el-table
            v-loading="listLoading"
            :data="sessionList"
            element-loading-text="加载中..."
            border
            fit
            highlight-current-row
            style="width: 100%;"
          >
            <el-table-column label="ID" align="center" width="80">
              <template slot-scope="scope">
                <span>{{ scope.row.id }}</span>
              </template>
            </el-table-column>
            
            <el-table-column label="访客信息" align="center" min-width="150">
              <template slot-scope="scope">
                <div v-if="scope.row.userId">
                  <el-tag type="success">注册用户</el-tag>
                  <div>ID: {{ scope.row.userId }}</div>
                </div>
                <div v-else>
                  <el-tag>访客</el-tag>
                  <div>{{ scope.row.visitorId }}</div>
                </div>
                <div>{{ scope.row.visitorName || '匿名访客' }}</div>
              </template>
            </el-table-column>
            
            <el-table-column label="来源页面" align="center" min-width="150">
              <template slot-scope="scope">
                <span>{{ scope.row.source || '-' }}</span>
              </template>
            </el-table-column>
            
            <el-table-column label="最后消息" align="center" min-width="200">
              <template slot-scope="scope">
                <div>{{ scope.row.lastMessage || '暂无消息' }}</div>
                <small>{{ formatTime(scope.row.lastTime) }}</small>
              </template>
            </el-table-column>
            
            <el-table-column label="评价" align="center" width="120">
              <template slot-scope="scope">
                <div v-if="scope.row.evaluationScore">
                  <el-rate
                    v-model="scope.row.evaluationScore"
                    disabled
                    text-color="#ff9900"
                  />
                </div>
                <span v-else>-</span>
              </template>
            </el-table-column>
            
            <el-table-column label="状态" align="center" width="100">
              <template slot-scope="scope">
                <el-tag :type="getStatusType(scope.row.status)">
                  {{ getStatusText(scope.row.status) }}
                </el-tag>
              </template>
            </el-table-column>
            
            <el-table-column label="创建时间" align="center" width="160">
              <template slot-scope="scope">
                <span>{{ formatTime(scope.row.createTime) }}</span>
              </template>
            </el-table-column>
            
            <el-table-column label="操作" align="center" width="200" class-name="small-padding fixed-width">
              <template slot-scope="scope">
                <el-button
                  size="mini"
                  type="primary"
                  @click="handleViewSession(scope.row)"
                >
                  查看
                </el-button>
                <el-button
                  size="mini"
                  v-if="scope.row.status === 0"
                  type="warning"
                  @click="handleEndSession(scope.row)"
                >
                  结束
                </el-button>
                <el-button
                  size="mini"
                  type="danger"
                  @click="handleDeleteSession(scope.row)"
                >
                  删除
                </el-button>
              </template>
            </el-table-column>
          </el-table>

          <!-- 分页 -->
          <pagination
            v-show="total > 0"
            :total="total"
            :page.sync="listQuery.pageNum"
            :limit.sync="listQuery.pageSize"
            @pagination="getSessionList"
          />
        </el-tab-pane>
        
        <el-tab-pane label="会话详情" name="chat" v-if="currentSession.sessionId">
          <div class="chat-container">
            <div class="session-info">
              <h3>
                {{ currentSession.visitorName || '访客' }}
                <el-tag size="small" :type="getStatusType(currentSession.status)">
                  {{ getStatusText(currentSession.status) }}
                </el-tag>
              </h3>
              <p v-if="currentSession.userId">用户ID: {{ currentSession.userId }}</p>
              <p v-else>访客ID: {{ currentSession.visitorId }}</p>
              <p>来源: {{ currentSession.source || '未知' }}</p>
              <p>创建时间: {{ formatTime(currentSession.createTime) }}</p>
              <div v-if="currentSession.evaluationScore">
                <p>评价: 
                  <el-rate
                    v-model="currentSession.evaluationScore"
                    disabled
                    text-color="#ff9900"
                  />
                </p>
                <p>评价内容: {{ currentSession.evaluationContent || '无评价内容' }}</p>
              </div>
              <div class="session-actions">
                <el-button
                  v-if="currentSession.status === 0"
                  type="warning"
                  size="small"
                  @click="handleEndSession(currentSession)"
                >
                  结束会话
                </el-button>
                <el-button
                  type="primary"
                  size="small"
                  @click="activeTab = 'sessions'"
                >
                  返回列表
                </el-button>
              </div>
            </div>
            
            <div class="message-list" ref="messageContainer">
              <div v-for="(message, index) in messageList" :key="index" 
                class="message" 
                :class="{'message-visitor': message.senderType === 0, 'message-service': message.senderType === 1}"
              >
                <div class="message-sender">
                  {{ message.senderType === 0 ? (currentSession.visitorName || '访客') : '客服' }}:
                </div>
                <div class="message-content">
                  <div v-if="message.messageType === 0" class="text-message">{{ message.content }}</div>
                  <div v-else-if="message.messageType === 1" class="image-message">
                    <img :src="message.content" alt="图片" @click="handlePreviewImage(message.content)" />
                  </div>
                  <div v-else-if="message.messageType === 2" class="file-message">
                    <i class="el-icon-document"></i>
                    <a :href="message.content" target="_blank">下载文件</a>
                  </div>
                </div>
                <div class="message-time">{{ formatTime(message.createTime) }}</div>
              </div>
              
              <div v-if="messageLoading" class="loading-messages">
                <i class="el-icon-loading"></i> 加载中...
              </div>
              
              <div v-if="messageList.length === 0 && !messageLoading" class="no-messages">
                暂无消息记录
              </div>
            </div>
            
            <div class="message-input" v-if="currentSession.status === 0">
              <div class="input-tools">
                <el-tooltip content="发送图片" placement="top">
                  <i class="el-icon-picture-outline" @click="selectImage"></i>
                </el-tooltip>
                <el-tooltip content="发送文件" placement="top">
                  <i class="el-icon-upload" @click="selectFile"></i>
                </el-tooltip>
                <input
                  type="file"
                  ref="imageInput"
                  accept="image/*"
                  style="display: none"
                  @change="uploadImage"
                />
                <input
                  type="file"
                  ref="fileInput"
                  style="display: none"
                  @change="uploadFile"
                />
              </div>
              
              <el-input
                v-model="inputMessage"
                type="textarea"
                :rows="3"
                placeholder="请输入回复内容"
                @keyup.enter.native="handleEnter"
              ></el-input>
              
              <div class="input-actions">
                <el-button 
                  type="primary" 
                  @click="sendMessage"
                  :disabled="!inputMessage.trim() && !uploadedFile"
                >
                  发送
                </el-button>
              </div>
            </div>
            
            <div v-else class="session-ended">
              会话已{{ currentSession.status === 1 ? '结束' : '评价' }}，无法继续发送消息
            </div>
          </div>
        </el-tab-pane>
      </el-tabs>
    </el-card>
    
    <!-- 图片预览 -->
    <el-dialog :visible.sync="previewVisible" append-to-body>
      <img width="100%" :src="previewImage" alt="预览图片" />
    </el-dialog>
  </div>
</template>

<script>
import { 
  getSessionList, 
  getSession, 
  updateSessionStatus, 
  getSessionMessages, 
  sendMessage,
  updateSessionMessagesStatus
} from '@/api/customerService'
// import Pagination from '@/components/Pagination'
// import waves from '@/directive/waves'

export default {
  name: 'CustomerServiceManagement',
  components: { Pagination },
  directives: { waves },
  data() {
    return {
      activeTab: 'sessions',
      listLoading: false,
      messageLoading: false,
      sessionList: [],
      total: 0,
      listQuery: {
        pageNum: 1,
        pageSize: 10,
        status: null,
        keyword: ''
      },
      currentSession: {},
      messageList: [],
      inputMessage: '',
      uploadedFile: null,
      previewVisible: false,
      previewImage: '',
      refreshInterval: null
    }
  },
  created() {
    this.getSessionList()
  },
  mounted() {
    // 每30秒刷新一次会话列表和消息
    this.refreshInterval = setInterval(() => {
      if (this.activeTab === 'sessions') {
        this.getSessionList()
      } else if (this.activeTab === 'chat' && this.currentSession.sessionId) {
        this.getMessageList()
      }
    }, 30000)
  },
  beforeDestroy() {
    if (this.refreshInterval) {
      clearInterval(this.refreshInterval)
    }
  },
  methods: {
    getSessionList() {
      this.listLoading = true
      getSessionList(this.listQuery).then(response => {
        this.sessionList = response.data
        this.total = response.total
        this.listLoading = false
      }).catch(() => {
        this.listLoading = false
      })
    },
    handleFilter() {
      this.listQuery.pageNum = 1
      this.getSessionList()
    },
    formatTime(timestamp) {
      if (!timestamp) return '-'
      
      const date = new Date(timestamp)
      return date.toLocaleString()
    },
    getStatusType(status) {
      switch (status) {
        case 0: return 'success'
        case 1: return 'info'
        case 2: return 'warning'
        default: return 'info'
      }
    },
    getStatusText(status) {
      switch (status) {
        case 0: return '进行中'
        case 1: return '已结束'
        case 2: return '已评价'
        default: return '未知'
      }
    },
    handleViewSession(row) {
      this.currentSession = { ...row }
      this.getMessageList()
      this.activeTab = 'chat'
    },
    handleEndSession(row) {
      this.$confirm('确认结束此会话?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        updateSessionStatus(row.sessionId, 1).then(response => {
          if (response.code === 200) {
            this.$message.success('会话已结束')
            if (this.activeTab === 'chat') {
              // 刷新当前会话
              this.getSession(row.sessionId)
            } else {
              // 刷新列表
              this.getSessionList()
            }
          } else {
            this.$message.error('操作失败: ' + response.message)
          }
        })
      }).catch(() => {
        // 取消操作
      })
    },
    handleDeleteSession(row) {
      this.$confirm('此操作将永久删除该会话及其所有消息记录, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        // 在这里实现删除逻辑
        this.$message.success('会话已删除')
        this.getSessionList()
      }).catch(() => {
        // 取消操作
      })
    },
    getSession(sessionId) {
      getSession(sessionId).then(response => {
        if (response.code === 200) {
          this.currentSession = response.data
        }
      })
    },
    getMessageList() {
      if (!this.currentSession.sessionId) return
      
      this.messageLoading = true
      getSessionMessages(this.currentSession.sessionId).then(response => {
        if (response.code === 200) {
          this.messageList = response.data
          this.scrollToBottom()
          
          // 更新所有访客消息为已读状态
          updateSessionMessagesStatus(this.currentSession.sessionId, 1)
        }
        this.messageLoading = false
      }).catch(() => {
        this.messageLoading = false
      })
    },
    scrollToBottom() {
      this.$nextTick(() => {
        if (this.$refs.messageContainer) {
          this.$refs.messageContainer.scrollTop = this.$refs.messageContainer.scrollHeight
        }
      })
    },
    handleEnter(e) {
      if (e.ctrlKey || e.metaKey) {
        // Ctrl+Enter 换行
        this.inputMessage += '\n'
      } else {
        // Enter 直接发送
        e.preventDefault()
        this.sendMessage()
      }
    },
    sendMessage() {
      if ((!this.inputMessage.trim() && !this.uploadedFile) || this.messageLoading) return
      
      const content = this.inputMessage.trim() || (this.uploadedFile ? this.uploadedFile.url : '')
      const messageType = this.uploadedFile ? 
                        (this.uploadedFile.type.startsWith('image/') ? 1 : 2) : 0
      
      const messageData = {
        sessionId: this.currentSession.sessionId,
        senderType: 1, // 客服发送
        messageType: messageType, // 消息类型: 0-文本, 1-图片, 2-文件
        content: content,
        status: 0 // 未读
      }
      
      sendMessage(messageData).then(response => {
        if (response.code === 200) {
          this.inputMessage = ''
          this.uploadedFile = null
          this.getMessageList()
        } else {
          this.$message.error('发送消息失败: ' + response.message)
        }
      }).catch(() => {
        this.$message.error('发送消息失败')
      })
    },
    selectImage() {
      this.$refs.imageInput.click()
    },
    selectFile() {
      this.$refs.fileInput.click()
    },
    uploadImage(e) {
      const file = e.target.files[0]
      if (!file) return
      
      // 模拟上传图片，实际项目中需要调用真实的上传API
      const mockImageUrl = URL.createObjectURL(file)
      this.uploadedFile = {
        url: mockImageUrl,
        name: file.name,
        type: file.type
      }
      
      // 上传成功后自动发送
      this.sendMessage()
      
      // 清空文件选择器
      e.target.value = ''
    },
    uploadFile(e) {
      const file = e.target.files[0]
      if (!file) return
      
      // 模拟上传文件，实际项目中需要调用真实的上传API
      const mockFileUrl = URL.createObjectURL(file)
      this.uploadedFile = {
        url: mockFileUrl,
        name: file.name,
        type: file.type
      }
      
      // 上传成功后自动发送
      this.sendMessage()
      
      // 清空文件选择器
      e.target.value = ''
    },
    handlePreviewImage(url) {
      this.previewImage = url
      this.previewVisible = true
    }
  }
}
</script>

<style scoped>
.customer-service-container {
  padding: 20px;
}

.filter-container {
  display: flex;
  align-items: center;
  gap: 10px;
  margin-bottom: 20px;
}

.chat-container {
  display: grid;
  grid-template-columns: 250px 1fr;
  grid-template-rows: 1fr auto;
  gap: 20px;
  height: 600px;
}

.session-info {
  grid-column: 1;
  grid-row: 1 / span 2;
  border-right: 1px solid #e0e0e0;
  padding-right: 20px;
}

.session-info h3 {
  margin-top: 0;
  display: flex;
  align-items: center;
  gap: 10px;
}

.session-actions {
  margin-top: 20px;
}

.message-list {
  grid-column: 2;
  grid-row: 1;
  overflow-y: auto;
  padding: 10px;
  background-color: #f9f9f9;
  border-radius: 4px;
}

.message {
  margin-bottom: 15px;
}

.message-visitor {
  text-align: left;
}

.message-service {
  text-align: right;
}

.message-sender {
  font-weight: bold;
  margin-bottom: 5px;
}

.message-content {
  display: inline-block;
  max-width: 70%;
  padding: 10px;
  border-radius: 8px;
  word-break: break-word;
}

.message-visitor .message-content {
  background-color: #fff;
  border: 1px solid #e0e0e0;
  text-align: left;
}

.message-service .message-content {
  background-color: #e1f3ff;
  text-align: left;
}

.text-message {
  white-space: pre-wrap;
}

.image-message img {
  max-width: 200px;
  max-height: 200px;
  border-radius: 4px;
  cursor: pointer;
}

.file-message {
  display: flex;
  align-items: center;
}

.file-message i {
  margin-right: 5px;
}

.message-time {
  font-size: 12px;
  color: #999;
  margin-top: 5px;
}

.message-input {
  grid-column: 2;
  grid-row: 2;
  border-top: 1px solid #e0e0e0;
  padding-top: 10px;
}

.input-tools {
  margin-bottom: 10px;
  display: flex;
  gap: 10px;
}

.input-tools i {
  font-size: 18px;
  color: #666;
  cursor: pointer;
}

.input-tools i:hover {
  color: #409EFF;
}

.input-actions {
  display: flex;
  justify-content: flex-end;
  margin-top: 10px;
}

.loading-messages {
  text-align: center;
  padding: 10px;
  color: #999;
}

.no-messages {
  text-align: center;
  padding: 20px;
  color: #999;
}

.session-ended {
  grid-column: 2;
  grid-row: 2;
  text-align: center;
  color: #999;
  padding: 20px;
  border-top: 1px solid #e0e0e0;
}
</style> 